package com.anlogic.sdk.bootimage.internal;

import com.anlogic.sdk.bootimage.internal.ui.BootgenDialog;
import com.anlogic.sdk.bootimage.model.BootGenModel;
import com.anlogic.sdk.bootimage.utils.BootGenPreferencesUtils;
import com.anlogic.sdk.utils.UtilsPlugin;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.commands.IHandler;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.jobs.IJobChangeEvent;
import org.eclipse.core.runtime.jobs.IJobChangeListener;
import org.eclipse.core.runtime.jobs.JobChangeAdapter;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.console.MessageConsole;
import org.eclipse.ui.handlers.HandlerUtil;

public class CreateBootImageHandler extends AbstractHandler implements IHandler {
	public Object execute(ExecutionEvent event) throws ExecutionException {
		IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindowChecked(event);
		BootGenModel model = loadModel();
		BootgenDialog dialog = new BootgenDialog(window.getShell());
		dialog.setModel(model);
		if (dialog.open() != 0)
			return null;
		createBootImage(dialog.getModel());
		return null;
	}

	private BootGenModel loadModel() {
		BootGenModel model = BootGenPreferencesUtils.loadBootgenModel();
		return model;
	}

	protected void createBootImage(BootGenModel model) {
		BootGenPreferencesUtils.savePreferences(model);
		MessageConsole console = UtilsPlugin.getDefault().getMessageConsole("Bootgen");
		BootgenJob bootgenJob = new BootgenJob("Create Boot Image", model,
				UtilsPlugin.getDefault().getLauncher(console));
		bootgenJob.setUser(true);
		bootgenJob.addJobChangeListener((IJobChangeListener) new JobChangeAdapter() {
			public void done(IJobChangeEvent event) {
				CreateBootImageHandler.this.findAndRefreshProject(model.getBifFile());
			}
		});
		bootgenJob.schedule();
	}

	protected void findAndRefreshProject(String bifFile) {
		IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
		if (bifFile.startsWith(root.getLocation().toOSString())) {
			Path path = new Path(bifFile);
			IPath iPath = path.makeRelativeTo(root.getLocation());
			if (iPath.segmentCount() > 0) {
				IProject project = root.getProject(iPath.segment(0));
				if (project.exists()) {
					try {
						project.refreshLocal(2, null);
					} catch (CoreException coreException) {
						
					}
					return;
				}
			}
		}
	}
}
